package com.ilock.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.ilock.bean.Ibike;
import com.ilock.bean.Ilockinfo;
import com.ilock.service.IBikeService;
import com.ilock.service.ILockService;
import com.ilock.service.IPictureService;

public class BikeAction extends ActionSupport {

	private IBikeService IBikeService;
	private ILockService ILockService;
	private IPictureService IPictureService;
	private Map<String, Object> bikeMap;
	private int lockID;
	private String lockpassword;
	private String description;
	private List<File> my = new ArrayList<File>();    
    private List<String> myFileName = new ArrayList<String>();  
    private List<String> myContentType = new ArrayList<String>();    //文件名  
    
/*	private File single;
    private String singleFileName;
    private String singleContentType;*/
    
    private static final int BUFFER_SIZE = 16 * 1024;  
	
	
	public IBikeService getIBikeService() {
		return IBikeService;
	}
	public void setIBikeService(IBikeService iBikeService) {
		IBikeService = iBikeService;
	}
	public ILockService getILockService() {
		return ILockService;
	}
	public void setILockService(ILockService iLockService) {
		ILockService = iLockService;
	}
	
	public IPictureService getIPictureService() {
		return IPictureService;
	}
	public void setIPictureService(IPictureService iPictureService) {
		IPictureService = iPictureService;
	}
	public Map<String, Object> getBikeMap() {
		return bikeMap;
	}
	public void setBikeMap(Map<String, Object> bikeMap) {
		this.bikeMap = bikeMap;
	}
	public int getLockID() {
		return lockID;
	}
	public void setLockID(int lockID) {
		this.lockID = lockID;
	}
	public String getLockpassword() {
		return lockpassword;
	}
	public void setLockpassword(String lockpassword) {
		this.lockpassword = lockpassword;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}

	public List<File> getMy() {
		return my;
	}
	public void setMy(List<File> my) {
		this.my = my;
	}
	public List<String> getMyFileName() {
		return myFileName;
	}
	public void setMyFileName(List<String> myFileName) {
		this.myFileName = myFileName;
	}
	public List<String> getMyContentType() {
		return myContentType;
	}
	public void setMyContentType(List<String> myContentType) {
		this.myContentType = myContentType;
	}
	/*public File getSingle() {
		return single;
	}
	public void setSingle(File single) {
		this.single = single;
	}
	public String getSingleFileName() {
		return singleFileName;
	}
	public void setSingleFileName(String singleFileName) {
		this.singleFileName = singleFileName;
	}
	public String getSingleContentType() {
		return singleContentType;
	}
	public void setSingleContentType(String singleContentType) {
		this.singleContentType = singleContentType;
	}*/
	
	
	public String getBike()throws Exception{
		Map<String,Object> tempMap = new HashMap<String,Object>(); 
		if(lockID!=0){
			if(ILockService.checkUserIDExist(lockID)!=null){
				Ibike bike = IBikeService.getBikeByLockId(lockID);
				List imageList = IPictureService.getPictureUrlByLockId(lockID);
				tempMap.put("bike", bike);
				tempMap.put("imageList", imageList);
				tempMap.put("state", "success");
			}else{
				tempMap.put("state", "lockID error");
			}
		}else{
			tempMap.put("state", "lockID empty");
		}
		this.setBikeMap(tempMap);
		return "success";
	}
	
	public String addBike()throws Exception{
		Map<String,Object> tempMap = new HashMap<String,Object>(); 
		if(lockpassword!=null && description!=null){
			Ilockinfo ilockinfo = ILockService.findLockInfoByToken(lockpassword);
			if(ilockinfo!=null){
				int lockID = ilockinfo.getIlockInfoNumber();
				//不校验是否存在，直接覆盖原来的内容
				Ibike bike = IBikeService.getBikeByLockId(lockID);
				if (!my.isEmpty()){
					System.out.println(my);
					System.out.println("picture not empty");
					System.out.println("my.size:"+my.size());
					//删除旧图片
					IPictureService.deletePictureByLockId(lockID);
			        for (int i = 0; i < my.size(); i++) {
			        	
			        	System.out.println(myFileName.get(i)+ "|| "+myContentType.get(i));
			        	String imageName = new Date().getTime()+ getExtention(myFileName.get(i));
			            String path = ServletActionContext.getServletContext()  
			                    .getRealPath("userimages")     
			                     +"\\"+ imageName;
			            String workspacepath = "C:\\Users\\Administrator\\git\\i-lock\\ILock\\WebRoot\\userimages\\"+imageName;
			            File imageFile = new File(path);   
			            File workspaceimageFile = new File(workspacepath);   
			            copy(my.get(i), imageFile); 
			            copy(my.get(i), workspaceimageFile); 
			            IPictureService.addPicture(lockID, "userimages\\"+imageName);
			        }  
				}else{
					System.out.println("picture empty");
					tempMap.put("imagestate", "image empty");
				}
				/*if (single != null){
					System.out.println(single);
					System.out.println("picture not empty");
					//删除旧图片
					IPictureService.deletePictureByLockId(lockID);
					System.out.println(singleFileName+ "|| "+singleContentType);
		        	String imageName = new Date().getTime()+ getExtention(singleFileName);
		            String path = ServletActionContext.getServletContext()  
		                    .getRealPath("userimages")     
		                     +"\\"+ imageName;
		            String workspacepath = "C:\\Users\\Administrator\\git\\i-lock\\ILock\\WebRoot\\userimages\\"+imageName;
		            File imageFile = new File(path);   
		            File workspaceimageFile = new File(workspacepath);   
		            copy(single, imageFile); 
		            copy(single, workspaceimageFile); 
		            IPictureService.addPicture(lockID, "userimages\\"+imageName); 
				}else{
					System.out.println("picture empty");
					tempMap.put("imagestate", "image empty");
				}*/
				if(bike==null){
				Ibike tempbike = new Ibike();
				tempbike.setIlockInfoNumber(ilockinfo.getIlockInfoNumber());
				tempbike.setDescription(description);
				IBikeService.addBike(lockID, description);
				tempMap.put("bike", tempbike);
				tempMap.put("state", "success");
				}else{
					Ibike tempbike = bike;
					tempbike.setDescription(description);
					IBikeService.updateBike(bike);
					tempMap.put("state", "bike info update success");
				}
			}else{
				tempMap.put("state", "locktoken error");
			}
		}else{
			tempMap.put("state", "info incompleted");
		}
		this.setBikeMap(tempMap);
		return "success";
	}
	
	private static void copy(File src, File dst) {  
        try {  
            InputStream in = null;  
            OutputStream out = null;  
            try {  
                in = new BufferedInputStream(new FileInputStream(src),  
                        BUFFER_SIZE);  
                out = new BufferedOutputStream(new FileOutputStream(dst),  
                        BUFFER_SIZE);  
                byte[] buffer = new byte[BUFFER_SIZE];  
                while (in.read(buffer) > 0) {  
                    out.write(buffer);  
                }  
            } finally {  
                if (null != in) {  
                    in.close();  
                }  
                if (null != out) {  
                    out.close();  
                }  
            }  
        } catch (Exception e) {
            e.printStackTrace();  
        }  
    }  
      
    private static String getExtention(String fileName) {  
        int pos = fileName.lastIndexOf(".");  
        return fileName.substring(pos);  
    }  
}
